package cn.itcast.tanhua.sso.controller;

import cn.itcast.tanhua.common.pojo.User;
import cn.itcast.tanhua.sso.service.UserService;
import cn.itcast.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description 用户登录
 * @Author WU
 * @Date 2021/5/24 21:49
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
    * @Description: 用户登录接口
    * @Param: phone、code，用map接收
    * @return: 返回
    * @Author: Mr.Tan
    * @Date: 2021/5/24
    */
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){
//        controller层调用业务层方法后要使用try。。catch，防止业务层中抛出异常继而抛到前端
        try {
//              获取参数
            String phone = param.get("phone");
            String code = param.get("verificationCode");
//        调用userService层login方法
            String data =this.userService.login(phone,code);
//         返回值不为空则登录成功
            if (StringUtils.isNotEmpty(data)) {
                Map<String,Object> result=new HashMap<>(2);
    //            将data切割成数组
                String[] ss = StringUtils.split(data, "|");
                result.put("token", ss[0]);
                result.put("isNew", Boolean.valueOf(ss[1]));
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);

    }


    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token){
        return this.userService.queryUserByToken(token);
    }
}
